package com.shihan.rabbitmq.demo.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description RabbitMQ 的配置类，只需要声明 Queue 和 Exchange，并进行绑定即可；
 *              TODO 关于 RabbitMQ 的其他配置，需要后续深入学习后才能使用！
 * @Author shihan
 * @Date 2021/1/9 22:54
 * @Version 1.0
 */
@Configuration
public class RabbitMQConfig {

    // 配置延迟交换器相关内容
    public static final String EXCHANGE_NAME_DELAYED = "exc.name.delayed";

    public static final String QUEUE_NAME_DELAYED = "queue.name.delayed";

    public static final String BINDING_KEY_DELAYED = "key.bind.delayed";

    /**
     * 声明一个普通队列即可
     *
     * @return
     */
    @Bean
    public Queue getQueue() {
        return new Queue(QUEUE_NAME_DELAYED, false, false, false, null);
    }

    /**
     * 安装好插件之后，创建一个 延迟交换器
     *
     * @return
     */
    @Bean
    public Exchange getDelayedMessageExchange() {
        // Exchange 配置信息的 Map 集合：指明交换器类型
        Map<String, Object> exchangeProps = new HashMap<>();
        exchangeProps.put("x-delayed-type", ExchangeTypes.DIRECT);

        // 创建一个 定制化的交换器，明确指明类型为 "x-delayed-message" 即延迟交换器，并且需要用到上述的 Map 配置集合；
        Exchange exchange = new CustomExchange(EXCHANGE_NAME_DELAYED, "x-delayed-message", false, false, exchangeProps);
        return exchange;
    }

    /**
     * 绑定 延迟队列 和 Queue
     * @return
     */
    @Bean
    public Binding getBinding() {
        return BindingBuilder.bind(getQueue()).to(getDelayedMessageExchange()).with(BINDING_KEY_DELAYED).noargs();
    }

    // 配置普通交换器、队列
    public static final String QUEUE_NAME_COMM = "queue.name.comm";

    public static final String EXCHANGE_NAME_COMM = "exc.name.comm";

    public static final String BINDING_KEY_COMM = "key.comm";

    @Bean
    public Queue commQueue(){
        return new Queue(QUEUE_NAME_COMM,false,false,false,null);
    }

    @Bean
    public Exchange commExchange(){
        return new DirectExchange(EXCHANGE_NAME_COMM,false,false,null);
    }

    @Bean
    public Binding commBinding(){
        return BindingBuilder.bind(commQueue()).to(commExchange()).with(BINDING_KEY_COMM).noargs();
    }

}
